using System;
using System.Collections;
using Sedna.Core.Persistence;
using Spring.Util;

namespace Sedna.Util
{
    public class CollectionProvider : IDataProvider
    {
        private string sortExpression;
        private bool isAsc = true;
        private int amount;
        private int startIndex;
        private ICollection data;

        public CollectionProvider(ICollection data)
        {
            this.data = data;
            amount = data.Count;
        }

        public CollectionProvider(ICollection data, String sortExpression, bool isAsc) 
            : this(data)
        {
            this.sortExpression = sortExpression;
            this.isAsc = isAsc;
        }
        
        public int StartIndex
        {
            get { return startIndex; }
            set { startIndex = value; }
        }

        public int Amount
        {
            get { return amount; }
            set { amount = value; }
        }

        public bool IsAsc
        {
            get { return isAsc; }
            set { isAsc = value; }
        }

        public string SortExpression
        {
            get { return sortExpression; }
            set { sortExpression = value; }
        }

        public ICollection LoadData()
        {
            ArrayList result = new ArrayList(data);
            if (!StringUtils.IsNullOrEmpty(SortExpression))
            {
                result.Sort(new PropertyComparer(SortExpression, IsAsc) );
            }
            
            if (StartIndex < 0 || Amount < 0)
            {
                return result;
            }
            
            if (StartIndex < result.Count)
            {
                return result.GetRange(StartIndex, Math.Min(result.Count - StartIndex, Amount));
            }

            return Collections.EMPTY_LIST;
        }

        public int TotalAmount
        {
            get { return data.Count;}
        }
        
        public IList Data
        {
            get { return new ArrayList(data); }
        }

        public CollectionProvider Clone(ICollection data)
        {
            CollectionProvider result = new CollectionProvider(data, SortExpression, IsAsc);
            result.StartIndex = StartIndex;
            result.Amount = Amount;

            return result;
        }
        
        public object Clone()
        {
            return Clone(data);
        }
    }
}
